package com.ruleengine.executer.impl;

import org.apache.log4j.Logger;

import com.ruleengine.context.IWorkflowConext;
import com.ruleengine.endpoint.data.IEndpointData;
import com.ruleengine.executer.InstructionExecuter;
import com.ruleengine.executer.exception.InstructionExecuteException;
import com.ruleengine.instruction.impl.CallWorkflowInstruction;
import com.ruleengine.router.manager.RuleEngineRouterManager;
import com.wx.express.calculator.ExpressCalculator;

public class CallWorkflowInstructionExecuter implements
        InstructionExecuter<CallWorkflowInstruction> {
    private static Logger logger = Logger
            .getLogger(CallWorkflowInstructionExecuter.class);

    public boolean execute(final IWorkflowConext context,
            final IEndpointData data, CallWorkflowInstruction instruction)
            throws InstructionExecuteException {
        // TODO Auto-generated method stub
        try {

            // 将要调用的工作流
            String realTarget = instruction.getTarget();
            if(logger.isDebugEnabled()){
                logger.debug("the original workflow task define is " + realTarget);
            }
            if ("expression".equals(instruction.getTargetType())) {
                // 表达式调用，需要先计算表达式的值
                realTarget = (String) (ExpressCalculator.instance()
                        .eval(instruction.getTarget(), new Object[] { context,
                                data }));
            }
            if(logger.isDebugEnabled()){
                logger.debug("the sub workflow task is " + realTarget);
            }
            // 调用路由器路由调用
            RuleEngineRouterManager.getInstance().getRuleEngineRouter().route(
                    realTarget, context, data);

        } catch (Exception e) {
            throw new InstructionExecuteException(e);
        }
        return true;
    }

}
